$(function() {
    var layer = layui.layer
    var form = layui.form

    getArtCateList()

    var indexAdd = null
    $('#btnAddCate').on('click', function() {
        indexAdd = layer.open({
            type: 1,
            title: '添加文章分类',
            area: ['500px', '250px'],
            content: $('#dialog-add').html() //这里content是一个普通的String
        })
    })

    $('body').on('submit', '#form-add', function(e) {
        e.preventDefault()
        $.ajax({
            type: 'post',
            url: '/my/article/addcates',
            data: $(this).serialize(),
            success: function(res) {
                if (res.status !== 0) {
                    return layer.msg('新增分类失败！')
                }
                getArtCateList()
                layer.msg('添加分类成功！')
                layer.close(indexAdd)
            }
        })
    })

    var indexEdit = null
    $('tbody').on('click', '.btn-edit', function() {
        indexEdit = layer.open({
            type: 1,
            title: '修改文章分类',
            area: ['500px', '250px'],
            content: $('#dialog-edit').html() //这里content是一个普通的String
        })
        var id = $(this).data('id')

        $.ajax({
            type: 'get',
            url: '/my/article/cates/' + id,
            success: function(res) {
                form.val('form-edit', res.data)
            }
        })
    })

    $('body').on('submit', '#form-edit', function(e) {
        e.preventDefault()
        $.ajax({
            method: 'post',
            url: '/my/article/updatecate',
            data: $(this).serialize(),
            success: function(res) {
                if (res.status !== 0) {
                    return layer.msg('更新分类数据失败！')
                }
                getArtCateList()
                layer.msg('更新分类数据成功！')
                layer.close(indexEdit)
            }
        })
    })


    $('tbody').on('click', '.btn-delete', function() {
        var id = $(this).data('id')
        layer.confirm('确认删除?', {
                icon: 3,
                title: '提示'
            },
            function(index) {
                $.ajax({
                    method: 'get',
                    url: '/my/article/deletecate/' + id,
                    success: function(res) {
                        if (res.status !== 0) {
                            return layer.msg('删除分类失败！')
                        }
                        layer.msg('删除分类成功！')
                        layer.close(index)
                        getArtCateList()
                    }
                })
            })
    })

    function getArtCateList() {
        $.ajax({
            type: 'get',
            url: '/my/article/cates',
            success: function(res) {
                var temp = template('tpl-table', res)
                $('tbody').html(temp)
            }
        })
    }
})